﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Openfree.Framework.DataAccess;
using System.Data;
using System.Text;

public partial class Controls_Activity_StockIn_Borrow : BaseUserControl
{
    private string TableName = "IC_StockIn";
    private string Key = "StockInID";
    private SqlCodeConfig codeConfig;
    private bool isreadonly;
    protected void Page_Load(object sender, EventArgs e)
    {
        InitLoadData();
        GoodItemSelect.OnGoodItemSelectOk += new GoodItemSelectEventHandler(btnSelectOk_Click);
    }
    private void InitLoadData()
    { 
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
        ReadOnlyData(false);
    }

    public void ReadOnlyData(bool IsReadOnly)
    {
        isreadonly = IsReadOnly;
        P_StockInDate.ReadOnly = IsReadOnly;
        P_SupplierID.ReadOnly = IsReadOnly;
        P_Description.ReadOnly = IsReadOnly;
        P_LoginName.ReadOnly = true;
        P_Department.ReadOnly = true;
    }
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        GoodItemSelect.OnSelect(sender, e);
    }
    private void ResetComponent()
    {
        hfStockInID.Value = string.Empty;
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
    }
    protected void btnSelectOk_Click(object sender, GoodItemSelectEventArgs e)
    {

        foreach (DataRow dr in e.SelectedRow)
        {
            DataRow row2 = SessionManager.DataSet.Tables["IC_StockInItem"].NewRow();

            row2["StockInItemID"] = System.Guid.NewGuid().ToString();
            row2["GoodsID"] = dr["GoodsID"];
            row2["GoodsCode"] = dr["GoodsCode"];
            row2["Subject"] = dr["Subject"];
            row2["CategoryName"] = dr["CategoryName"];
            row2["CategoryID"] = dr["CategoryID"];
            row2["GoodsMaker"] = dr["GoodsMaker"];
            row2["TypeModel"] = dr["TypeModel"];
            row2["GoodsUnit"] = dr["GoodsUnit"];
            row2["StandardCost"] = dr["StandardCost"]; 
            row2["GoodsCount"] = 0;
            row2["BadCount"] = 0;
            row2["OldCount"] = 0;
            row2["IsCheck"] = "未确认";
            SessionManager.DataSet.Tables["IC_StockInItem"].Rows.Add(row2);
        }
        BindGridViewItems();
    }

    public void ViewStockIn_Borrow(string stockInId)
    {
        this.isreadonly = true;
        ReadOnlyData(true);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select T.*" + PMSAccess.AppendSql_UserOrg + " from IC_StockIn T where T.StockInID='" + stockInId + "'", "IC_StockIn");
        SessionManager.DataSet = ds;
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select T.*,'已确认' as IsCheck,A.SUBJECT AS CategoryName from IC_StockInItem T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where StockInID='" + stockInId + "' ", "IC_StockInItem");
        if (ds.Tables["IC_StockIn"].Rows.Count > 0)
        {
            DataRow row = ds.Tables["IC_StockIn"].Rows[0];
            P_StockInDate.Text = row["StockInDate"].ToString();
            P_SupplierID.Text = row["SupplierID"].ToString();
            P_Description.Text = row["Description"].ToString();
            P_LoginName.Text = row["UserName"].ToString();
            P_Department.Text = row["OrgName"].ToString();
        }
        BindGridViewItems();
        btnSelect.Visible = false;
        btnSubmit.Visible = false;
        btnCancel.Text = "返回";
    }
    public void AddStockIn_Borrow()
    {
        this.isreadonly = false;
        ReadOnlyData(false);
        btnSelect.Visible = true;
        btnSubmit.Visible = true;
        btnCancel.Text = "取消";
        P_StockInDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        btnSearch_Click(null, null);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string cmdText = "SELECT T.*,A.CodeName AS StockOutTypeName" + PMSAccess.AppendSql_UserOrg + " FROM {0} T  LEFT JOIN " + SqlCodeConfig.TableName + " A ON A.CodeValue=T.StockOutType AND A.Category='" + PMSCodeCategory.PMS_CKLX + "' where 1=1 ";
        StringBuilder sql = new StringBuilder(string.Format(cmdText, "IC_StockOut"));
        sql.Append(" AND T.StockOutType = '").Append(PMSCodeCategory.PMS_CKLX_JieHuan).Append("'");
        sql.Append(" AND T.Status = '").Append(StockOutStatus.UnBack).Append("'");
        if (!string.IsNullOrEmpty(S_StockOutCode.Text))
        {
            sql.Append(" AND T.StockOutCode like '%").Append(S_StockOutCode.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_StockOutDate.Text))
        {
            sql.Append(" AND T.StockOutDate = '").Append(S_StockOutDate.Text).Append("'");
        } 
        sql.Append(" ORDER BY T.CREATETIME DESC");
        FillgridViewSelect(0, sql.ToString());
        hfModalPopup.Value = "SelectItem"; 

        modalPopup.Show();

    }
    public void btnSubmit_Click(object sender, EventArgs e)
    {
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from " + this.TableName + " where 1=2 ", this.TableName);
        DataRow dr = SessionManager.DataSet.Tables["IC_StockOut"].Rows[0];
        dr["Status"] = StockOutStatus.IsBack;
        DataRow row = SessionManager.DataSet.Tables[this.TableName].NewRow();
        string stockInId = System.Guid.NewGuid().ToString();
        row["Status"] = StockInStatus.IsStockIn;
        row["StockInID"] = stockInId;
        row["StockInCode"] = PMSAccess.GetCode(EnumCodeKind.RuKu);

        row["StockInDate"] = P_StockInDate.Text;
        row["StockInType"] = PMSCodeCategory.PMS_RKLX_LingLiao;
        row["SupplierID"] = P_SupplierID.Text;
        row["Description"] = P_Description.Text;
        row["LoginName"] = SessionManager.UserID;
        row["Department"] = SessionManager.OrgID;
        row["PurchaseOrderID"] = dr["RequisitionID"];
        PMSAccess.AppendValue(ref row, EnumOperator.ADD);
        SessionManager.DataSet.Tables[this.TableName].Rows.Add(row);
        //更新库存
        //获取当前库存信息
        if (SessionManager.DataSet.Tables.Contains("IC_Goods"))
            SessionManager.DataSet.Tables.Remove("IC_Goods");
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from IC_Goods ", "IC_Goods");

        DataTable _gooddt = SessionManager.DataSet.Tables["IC_Goods"];
        DataRow[] _gooddrs = null;
        foreach (DataRow _dr in SessionManager.DataSet.Tables["IC_StockInItem"].Rows)
        {
            _dr["StockInID"] = stockInId;
            //修改库存量:可用库存量和实际库存量
            _gooddrs = _gooddt.Select("GoodsID='" + _dr["GoodsID"].ToString() + "'");
            if (_gooddrs.Length > 0)
            {
                _gooddrs[0]["ActiveCount"] = Convert.ToInt32(_gooddrs[0]["ActiveCount"]) + Convert.ToInt32(_dr["GoodsCount"]);
                _gooddrs[0]["OldCount"] = Convert.ToInt32(_gooddrs[0]["OldCount"]) + Convert.ToInt32(_dr["OldCount"]);
                _gooddrs[0]["BadCount"] = Convert.ToInt32(_gooddrs[0]["BadCount"]) + Convert.ToInt32(_dr["BadCount"]);
            }
        }

        //一起更新
        PMSAccess.UpdateDataSet(this.Connection, new string[] { "IC_Goods", "IC_StockOut", "IC_StockIn", "IC_StockInItem" }, SessionManager.DataSet);
        this.btnCancel_Click(sender, e);
        Alert("领料入库完成");
    }
    protected void FillgridViewSelect(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "purchasecmdText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "purchasecmdText"] = cmdText;
        gridViewSelect.ShowFooter = true;
        gridViewSelect.NavigationData = splitPage.GetNavigationData(currentPage);
        gridViewSelect.DataSource = ds.Tables[0];
        gridViewSelect.DataBind();
    }
    protected void gridViewSelect_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillgridViewSelect(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "purchasecmdText"].ToString());
    }

    protected void btnModalPopupOK_Click(object sender, EventArgs e)
    {

        string stockOutID = Request["StockOutID"];
        if (string.IsNullOrEmpty(stockOutID))
        {
            base.Alert("请选择借用出库单或点击取消，非借还入库请点击其他入库");
            modalPopup.Show();
            return;
        } 
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select * from " + this.TableName + " where 1=2 ", this.TableName);
        SessionManager.DataSet = ds;
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select  T.* from IC_StockOut T where T.StockOutID ='" + stockOutID + "'", "IC_StockOut");
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select  T.*,A.SUBJECT AS CategoryName from IC_StockOutItem T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where T.StockOutID ='" + stockOutID + "'", "IC_StockOutItem");
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select  T.*,'未确认' as IsCheck,A.SUBJECT AS CategoryName from IC_StockInItem T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where 1=2 ", "IC_StockInItem");

        foreach (DataRow row in SessionManager.DataSet.Tables["IC_StockOutItem"].Rows)
        {
            DataRow row2 = SessionManager.DataSet.Tables["IC_StockInItem"].NewRow();
            foreach (DataColumn dc in SessionManager.DataSet.Tables["IC_StockOutItem"].Columns)
            {
                if (SessionManager.DataSet.Tables["IC_StockInItem"].Columns.Contains(dc.ColumnName))
                {
                    if (dc.ColumnName == "GoodsCount")
                    { 
                        row2["GoodsCount"] = 0;
                        row2["BadCount"] = 0;
                        row2["OldCount"] = 0;
                        row2["OrderCount"] = row[dc.ColumnName];
                    }
                    else
                    {
                        row2[dc.ColumnName] = row[dc.ColumnName];
                    }
                }
            }
            row2["IsCheck"] = "未确认";
            row2["StockInItemID"] = System.Guid.NewGuid().ToString();
            SessionManager.DataSet.Tables["IC_StockInItem"].Rows.Add(row2);
        }
        BindGridViewItems();
    }

    #region 具体项操作
    protected void BindGridViewItems()
    {
        DataTable dt = SessionManager.DataSet.Tables["IC_StockInItem"];
        gridViewItems.ShowFooter = false;
        gridViewItems.DataSource = dt;
        gridViewItems.DataBind();
        gridViewItems.Columns[12].Visible = !isreadonly;
        gridViewItems.Columns[13].Visible = !isreadonly;

    }
    protected void gridViewItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[0].Controls[0]).NavigateUrl = "~/PMSWeb/GoodDetail.aspx?GoodsID=" + ((HiddenField)e.Row.Cells[7].Controls[1]).Value;
            (e.Row.Cells[7].Controls[3] as TextBox).ReadOnly = isreadonly;
            (e.Row.Cells[8].Controls[1] as TextBox).ReadOnly = isreadonly;
            (e.Row.Cells[9].Controls[1] as TextBox).ReadOnly = isreadonly;
            (e.Row.Cells[10].Controls[1] as TextBox).ReadOnly = isreadonly;
        }
    }
    protected void gridViewItems_RowEditing(object sender, GridViewEditEventArgs e)
    {
        string ID = (gridViewItems.Rows[e.NewEditIndex].Cells[7].Controls[1] as HiddenField).Value;
        string txt = (gridViewItems.Rows[e.NewEditIndex].Cells[7].Controls[3] as TextBox).Text.Trim();
        string badtxt = (gridViewItems.Rows[e.NewEditIndex].Cells[8].Controls[1] as TextBox).Text.Trim();
        string oldtxt = (gridViewItems.Rows[e.NewEditIndex].Cells[9].Controls[1] as TextBox).Text.Trim();
        DataRow[] rows = SessionManager.DataSet.Tables["IC_StockInItem"].Select("GoodsID='" + ID + "'");
        int countIn = 0;
        if (rows.Length > 0)
        {
            try
            {
                countIn = Convert.ToInt32(txt);
                rows[0]["GoodsCount"] = countIn;
            }
            catch
            {
                Alert("未用数量请输入整数");
                return;
            }
            try
            {
                countIn = Convert.ToInt32(badtxt);
                rows[0]["BadCount"] = countIn;
            }
            catch
            {
                Alert("损耗/丢失数量请输入整数");
                return;
            }
            try
            {
                countIn = Convert.ToInt32(oldtxt);
                rows[0]["OldCount"] = countIn;
            }
            catch
            {
                Alert("旧料收回数量请输入整数");
                return;
            }
            rows[0]["IsCheck"] = "已确认";
            rows[0]["Description"] = (gridViewItems.Rows[e.NewEditIndex].Cells[10].Controls[1] as TextBox).Text.Trim();
        }
        BindGridViewItems();
    }

    protected void gridViewItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string ID = (gridViewItems.Rows[e.RowIndex].Cells[6].Controls[1] as HiddenField).Value;
        DataRow[] rows = SessionManager.DataSet.Tables["IC_StockInItem"].Select("GoodsID='" + ID + "'");
        if (rows.Length > 0)
        {
            foreach (DataRow row in rows)
            {
                if (row.RowState != DataRowState.Deleted)
                {
                    row.Delete();
                }
            }

        }
        BindGridViewItems();
    }
    public void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("StockInManager.aspx");
    }
    #endregion
}


